package com.syxp.pda.service.plan.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import org.springframework.transaction.annotation.Transactional;

import com.syxp.pda.core.util.ArraysBuilder;
import com.syxp.pda.dao.base.DepartmentDao;
import com.syxp.pda.dao.base.DutyDao;
import com.syxp.pda.dao.base.UserDao;
import com.syxp.pda.entity.base.Department;
import com.syxp.pda.entity.base.Duty;
import com.syxp.pda.entity.base.User;
import com.syxp.pda.service.plan.DutyUserService;

@Transactional
public class DutyUserServiceImpl implements DutyUserService {
	
	private DutyDao dutyDao;
	private UserDao userDao;
	private DepartmentDao deptDao;

	@Override
	public void add(int userId, int dutyId) {
		Duty duty = (Duty)dutyDao.get(dutyId);
		Set<User> users = duty.getUsers();
		User u = userDao.get(userId);
		users.add(u);
		dutyDao.update(duty);

	}

	@Override
	public void modify(int userId, int dutyId) {
		Duty duty = (Duty)dutyDao.get(dutyId);
		Set<User> users = duty.getUsers();
		users.clear();
		dutyDao.save(duty);
		User u = userDao.get(userId);
		users.add(u);
		dutyDao.update(duty);

	}


	@Override
	public void remove(int userId, int dutyId) {
		Duty duty = this.dutyDao.get(dutyId);
		Set<User> users = duty.getUsers();
		Iterator<User> it = users.iterator();
		while(it.hasNext()) {
			User user = it.next();
			if(user.getUserID()==userId) {
				users.remove(user);
				user = null;
				break;
			}
			user = null;
		}
		this.dutyDao.update(duty);
	}

	
	@Override
	public ArrayList getDutyUsers(int departmentId) {
		ArrayList dutyusers = new ArrayList();
		Department dept = this.deptDao.get(departmentId);
		//if(dept == null) return dutyusers;
		Set userSet = dept.getUsers();
		Iterator it = userSet.iterator();
		while(it.hasNext()){
			User user = (User)it.next();
			Set dutySet = user.getDutys();
			if(dutySet.size()>0) {
				user.setDutys(ArraysBuilder.buildSet(dutySet));
				dutyusers.add(user);
			}
		}
		return dutyusers;
	}
	
	/**
	 * @return the dutyDao
	 */
	public DutyDao getDutyDao() {
		return dutyDao;
	}

	/**
	 * @param dutyDao the dutyDao to set
	 */
	public void setDutyDao(DutyDao dutyDao) {
		this.dutyDao = dutyDao;
	}

	/**
	 * @return the userDao
	 */
	public UserDao getUserDao() {
		return userDao;
	}

	/**
	 * @param userDao the userDao to set
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * @return the deptDao
	 */
	public DepartmentDao getDeptDao() {
		return deptDao;
	}

	/**
	 * @param deptDao the deptDao to set
	 */
	public void setDeptDao(DepartmentDao deptDao) {
		this.deptDao = deptDao;
	}

}
